#!/bin/bash

#######################################################
# 
# 按天配置清理openGauss bin工具历史日志
#
#######################################################

set -e

CURRENT_DIR=$(dirname $(realpath $0))
LOG_CONFIG_FILE=logconfig.ini
STORAGE_DAYS=90

function read_ini()
{
    SECTION=$1; KEY=$2
    RESULT=`awk -F '=' '/\['$SECTION'\]/{a=1}a==1&&$1~/'$KEY'/{print $2;exit}' ${CURRENT_DIR}/${LOG_CONFIG_FILE}`
    echo $RESULT
}

function clear_log_remote()
{
    hostip=$1
    logfile=$2
    logpath=$(read_ini ${logfile} logpath)
    curfile="${logfile}-${current_date}"

    scp ${CURRENT_DIR}/local_clean_oglog.sh ${hostip}:~
    ssh ${hostip} sh ~/local_clean_oglog.sh $logfile $logpath $STORAGE_DAYS
}

function execute_eachhost()
{
    hostip=$1
    logfile_arr=$2
    echo ${logfile_arr[@]}
    for logfile in ${logfile_arr[@]} 
    do 
        if [ "${logfile}" != "" ]; then
            logfile=$(echo ${logfile// /})
        fi
        clear_log_remote "${hostip}" "${logfile}"
    done
}

function main()
{
    STORAGE_DAYS=$(read_ini common store_days)
    hostips=$(read_ini common hosts)
    echo "hostips is $hostips"
    echo "STORAGE_DAYS is $STORAGE_DAYS"
    logfiles=$(read_ini common logfiles)

    if [[ ! $STORAGE_DAYS =~ ^[0-9]+$ ]];then
        echo "STORAGE_DAYS[$STORAGE_DAYS] is not a number."
        exit 1
    fi

    OLD_IFS="$IFS" 
    IFS="," 
    host_arr=($hostips)
    logfile_arr=($logfiles)
    IFS="$OLD_IFS"
    for host in ${host_arr[@]}
    do
        if [ "${host}" != "" ]; then
            host=$(echo ${host// /})
            execute_eachhost "${host}" "${logfile_arr}"
        fi
    done
}

main $@